<?php

namespace app\service;

use think\facade\Cache;
use think\facade\Config;

/*
 * php声明一个对象是先声明class,然后实例化调用
 * 这个类是钉钉相关操作
 * private:私有 内部调用
 * public: 公开 外部调用
 * */

class Event
{
    public $attendees;
    public $description;
    public $summary;
    public $calendar_id = 'primary';
    public $organizer = [];
    public $end = [];
    public $start = [];
}

//class Event
//{
//    public $summary = '产品技术中心/web前端 test面试';
//    public $attendees = [
//        ['userid' => '15857033069202998']
//    ];
//
//    public $calendar_id = 'primary';
//
//    public $organizer = [
//        'userid' => '15857033069202998'
//    ];
//
//    public $end = [
//        'date' => '2020-07-24'
//    ];
//
//    public $start = [
//        'date' => '2020-07-23'
//    ];
//}



class DingNotice
{

    private function getAccessToken()
    {
        /*
         * 从redis中获取access_token,返回
         * 如果不存在,(appKey,appSecret)请求钉钉api,获取,并存储到redis
         * Config: [
                'agentId'      => '231781288',
                'corpId'       => 'dingfee9459144c03665',
                'corpSecret'   => 'QhviqBmyxne0nAlDhVNaTPKcjgUwW4PMc1kuHt_gicBpW8skU2H8Ref6EG8WnRJ',
                'appKey'       => 'dingvn2lsr9aqdros9qq',
                'appSecret'    => 'cbotXLxZgvwzauPcLY4jYMAPIqzbHaQSITIeblIK_wV0RMDX3n42lC2EDGG_6rAv'
            ];
         * */
        $redis = Cache::store('redis');
        $access_token = $redis->get('access_token');
        if(empty($access_token)){
            $url = sprintf("https://oapi.dingtalk.com/gettoken?appkey=%s&appsecret=%s",Config::get('dingding.appKey'),Config::get('dingding.appSecret'));
            $res = json_decode(curl_get($url),true);
            $access_token = $res['access_token'];
            $redis->set('access_token',$access_token,7000);
        }
        return $access_token;
    }

    // 企业工作通知消息
    public function companyMsg($useridList, $msgtype, $msgbody)
    {
        $params = [
            'agent_id' => Config::get('dingding.agentId'),
            'userid_list' => $useridList,
            'msg' => [
                "msgtype" => $msgtype,
                $msgtype => $msgbody,
            ],
        ];
        $result = $this->_post('topapi/message/corpconversation/asyncsend_v2', $params);
        return $result;
    }

    // 创建日程 https://ding-doc.dingtalk.com/doc#/serverapi2/iqel76
    public function calendarCreate($event)
    {
        $params = [
            'agentid' => Config::get('dingding.agentId'),
            'event' => $event
        ];
        $result = $this->_post('topapi/calendar/v2/event/create', $params);
        return $result;
    }

    // 修改 https://oapi.dingtalk.com/topapi/calendar/v2/event/update?access_token=ACCESS_TOKEN
    public function calendarUpdate($event)
    {
        $params = [
            'agentid' => Config::get('dingding.agentId'),
            'event' => $event
        ];
        $result = $this->_post('topapi/calendar/v2/event/update', $params);
        return $result;
    }

    // 取消日程 https://oapi.dingtalk.com/topapi/calendar/v2/event/cancel?access_token=ACCESS_TOKEN
    public function calendarDelete($event_id)
    {
        $params = [
            'agentid' => Config::get('dingding.agentId'),
            "calendar_id" => 'primary',
            'event_id' => $event_id
        ];
        $result = $this->_post('topapi/calendar/v2/event/cancel', $params);
        return $result;
    }
    
    // 新增/取消 参会人  https://oapi.dingtalk.com/topapi/calendar/v2/attendee/update?access_token=ACCESS_TOKEN
    public function changeAttendees($event_id,$attendees)
    {
        $params = [
            'agentid' => Config::get('dingding.agentId'),
            "calendar_id" => 'primary',
            'event_id' => $event_id,
            'attendees' => $attendees
        ];
        $result = $this->_post('topapi/calendar/v2/attendee/update', $params);
        return $result;
    }

    private function _post($api, $params)
    {
        /*
         * 二次封装请求方法
         * */
        $access_token = $this->getAccessToken();

        $url = 'https://oapi.dingtalk.com/' . $api . '?access_token=' . $access_token;

        $result = self::http($url, 'POST', json_encode($params, JSON_UNESCAPED_UNICODE), [
            'Content-Type' => 'application/json',
        ]);
        if ($result !== false) {
            $result = json_decode($result, true);
            if ($result['errcode'] == 0) {
                return $result;
            } else {
                return $result;
            }
        } else {
            return $result;
        }
    }

    public static function http($url, $method = 'GET', $postFields = null, $headers = null)
    {
        $method = strtoupper($method);
        if (!in_array($method, ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'])) {
            return false;
        }
        $opts = [
            CURLOPT_CUSTOMREQUEST  => $method,
            CURLOPT_URL            => $url,
            CURLOPT_FAILONERROR    => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_CONNECTTIMEOUT => 30,
        ];
        if ($method == 'POST' && !is_null($postFields)) {
            $opts[CURLOPT_POSTFIELDS] = $postFields;
        }
        if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == 'https') {
            $opts[CURLOPT_SSL_VERIFYPEER] = false;
            $opts[CURLOPT_SSL_VERIFYHOST] = false;
        }
        if (!empty($headers) && is_array($headers)) {
            $httpHeaders = [];
            foreach ($headers as $key => $value) {
                array_push($httpHeaders, $key . ':' . $value);
            }
            $opts[CURLOPT_HTTPHEADER] = $httpHeaders;
        }
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $data = curl_exec($ch);
        $err  = curl_errno($ch);
        curl_close($ch);
        if ($err > 0) {
            return false;
        } else {
            return $data;
        }
    }

}